#!/usr/bin/env python3
'''
The module that does everything according to what the user wants
'''
import argparse
import time
import sys
import signal
import os
import libtn


def cb_sighup(signum, frame):
    '''
    A signal handler that makes TN reread the cfg file

    Parameters:
    signum - signal number
    frame - current stack frame
    '''
    API.fmt.read_file()

if __name__ == '__main__':
    PARSER = argparse.ArgumentParser()
    PARSER.add_argument('-c', '--nick', help='Twitch nickname', default='')
    PARSER.add_argument('-i', '--interval', help='Interval between checks '
                        'in seconds. Default: 120', type=int, default=120)
    PARSER.add_argument('-n', '--online', help='Only check for online channels'
                        ' a user follows', action='store_true')
    PARSER.add_argument('-f', '--offline', help='Only check for offline'
                        ' channels a user follows', action='store_true')
    PARSER.add_argument('-v', '--verbose', help='Enable verbose output',
                        action='store_true')
    PARSER.add_argument('-u', '--user', help='Check status of user(,user)',
                        type=str)
    PARSER.add_argument('-t', '--token', help='Tokens are not needed anymore. '
                        'Option is left here for compability', type=str)
    PARSER.add_argument('-l', '--logfile', help='File used for logging events '
                        'in -c/--nick mode', type=str)
    PARSER.add_argument('-g', '--config', help='Path to configuration file',
                        type=str)

    ARGS = PARSER.parse_args()
    if not ARGS.nick and not ARGS.user:
        print('You have to pass atleast either -c/--nick or '
              '-u/--user to ' + sys.argv[0] + '!')
        sys.exit(1)

    CONFIG_FILE = os.environ.get('XDG_CONFIG_HOME',
                                 os.environ.get('HOME', '') + '/.config')
    CONFIG_FILE += '/twitchnotifier.cfg'

    if ARGS.config:
        CONFIG_FILE = ARGS.config

    if ARGS.verbose:
        print('Configuration file:', CONFIG_FILE)

    FMT = libtn.Settings(CONFIG_FILE)
    API = libtn.NotifyApi(ARGS.nick, FMT, ARGS.logfile, ARGS.verbose)
    signal.signal(signal.SIGHUP, cb_sighup)

    if ARGS.user:
        LST = ARGS.user.split(',')
        RET = API.check_if_online(LST)
        EXIT_CODE = 1
        for name, data in RET.items():
            if data[0] is True:
                EXIT_CODE = 0
            print(data[1])
        del API
        sys.exit(EXIT_CODE)

    try:
        ST = API.get_status()
    except NameError:
        print(ARGS.nick + ' is an invalid nickname!', file=sys.stderr)
        del API
        sys.exit(1)

    if ARGS.online:
        EXIT_CODE = 1
        for name, data in ST.items():
            if data[0]:
                EXIT_CODE = 0
                print(libtn.repl(data[1], name, API.fmt.list_entry['on']))
        del API
        sys.exit(EXIT_CODE)

    if ARGS.offline:
        EXIT_CODE = 1
        for name, data in ST.items():
            if not data[0]:
                EXIT_CODE = 0
                print(libtn.repl(data[1], name, API.fmt.list_entry['off']))
        del API
        sys.exit(EXIT_CODE)

    # Parse the initial statuses
    API.diff(ST)

    while True:
        time.sleep(ARGS.interval)
        API.diff(API.get_status())
